package net.oschina.simpleplus.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.Authorizer;
import org.apache.shiro.authz.ModularRealmAuthorizer;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;

@Configuration
public class ShiroConfiguration {

	@Bean("authorizer")
	public Authorizer authorizer(){
		return new ModularRealmAuthorizer();
	}
	
	@Bean("shiroCache")
	public CacheManager cacheManager(){
		return new MemoryConstrainedCacheManager();
	}
	
	
	@Bean
	public HashedCredentialsMatcher hashedCredentialsMatcher(){
		RetryLimitHashedCredentialsMatcher credentialsMatcher = new RetryLimitHashedCredentialsMatcher(Md5Hash.ALGORITHM_NAME, cacheManager());
		credentialsMatcher.setHashIterations(2);
		return credentialsMatcher;
	}
	
	@Bean
	public UserRealm realm(){
		UserRealm userRealm = new UserRealm();
		userRealm.setCredentialsMatcher(hashedCredentialsMatcher());
		userRealm.setCacheManager(cacheManager());
		return userRealm;
	}
	
	@Bean
	public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
        chainDefinition.addPathDefinition("/register", "anon");
        chainDefinition.addPathDefinition("/login", "anon");
        chainDefinition.addPathDefinition("/**", "authc");
        return chainDefinition;
    }
}